<template>
  <div class="dataSource">
    <el-dialog
      title="浏览文件"
      :visible.sync="dialogTableVisible"
      @close="handleCloseDialog"
    >
      <el-scrollbar style="height: 100%">
        <el-button type="text" disabled
          >当前路径:{{ dataSource.fileUrl }}</el-button
        >
        <el-button
          @click="handlePrevious"
          type="primary"
          size="mini"
          icon="el-icon-arrow-left"
          >返回上一级</el-button
        >
        <el-button @click="handleconfirm" type="primary" size="mini"
          >选择</el-button
        >
        <el-tree
          :data="gridData"
          :props="defaultProps"
          :default-expand-all="true"
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node }">
            <span>
              <i
                :class="
                  node.data.type === 2
                    ? 'el-icon-folder-opened'
                    : 'el-icon-s-order'
                "
              ></i
              >{{ node.label }}
            </span>
          </span>
        </el-tree>
      </el-scrollbar>
    </el-dialog>
    <el-divider content-position="left"> <i></i>数据来源 </el-divider>
    <el-form
      ref="form"
      :model="dataSource"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="协议类型" prop="databaseType">
        <el-select
          v-model="dataSource.databaseType"
          clearable
          placeholder="请选择"
          style="width: 220px"
          @change="chooseTypeEvent"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="database">
        <el-select
          v-model="dataSource.database"
          clearable
          placeholder="请选择"
          style="width: 220px"
        >
          <el-option
            v-for="item in databaseOptions"
            :key="item.id"
            :label="item.datasourceName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件路径" prop="fileUrl">
        <el-input
          v-model="dataSource.fileUrl"
          style="width: 220px"
          placeholder="请输入"
        ></el-input>
        <el-button
          size="small"
          type="primary"
          style="margin-left: 15px"
          @click="handleBrowsingFiles"
          >浏览文件</el-button
        >
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="dataSource.fileName"
          style="width: 220px"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <!-- <span style="color: red"
          >文件名：多个文件之间用/隔开(不填写默认为该文件夹下所有文件)</span
        > -->
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { typeGetDataSource } from "@/api/dataset/fileserver.js"
import { browsingFiles } from "@/api/task/fileserver.js"

export default {
  components: {},
  data () {
    return {
      gridData: [
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      dialogTableVisible: false,
      dataSource: {},
      filetypeOptions: [
        "未知", "普通文件", "目录文件", "块设备文件", "字符设备文件", "socket文件", "管道文件", "软链接文件"
      ],
      // 数据库类型字典
      typeOptions: [
        {
          label: "ftp",
          value: "ftp"
        },
        {
          label: "sftp",
          value: "sftp"
        }
      ],
      databaseOptions: [
      ],
      page: {
        pageNo: 1, // 当前位于哪页
        pageSize: 8, // 1页显示多少条
        total: 0
      },
      // 单表字段选择
      tableData: [],
      // 列表配置
      column: [
        {
          align: "center",
          name: "columnName",
          label: "字段名称"
        },
        {
          align: "center",
          name: "columnMemo",
          label: "字段别名"
        },
        {
          align: "center",
          name: "columnType",
          label: "字段类型"
        },
        {
          align: "center",
          name: "columnLong",
          label: "字段长度"
        }
      ],
      initSelection: [],
      // 多表选择
      tableSourceData: [],
      // initTableSourceData: []
      formRules: {}
    }
  },
  props: {
    initData: Object,
    mode: String
  },
  watch: {
    dataSource: {
      deep: true,
      handler: function (val) {
        this.$emit("input", val)
      }
    },
    initData: {
      deep: true,
      handler: async function (obj) {
        this.dataSource = {
          databaseType: obj.readerDatasourceType,
          database: obj.readerDatasourceId,
          fileUrl: obj.readFilePath || "/",
          fileName: obj.readFileName
        }
        await this.chooseTypeEvent()
      }
    }
  },
  methods: {
    //  确定选择文件
    handleconfirm () {
      if (this.NodeClickData.type === 2) {
        let addUrl = ""
        if (this.dataSource.fileUrl !== "/") {
          addUrl = "/"
        }
        this.dataSource.fileUrl += addUrl + this.NodeClickData.label
      }
      this.dialogTableVisible = false
    },
    //  初始化文件列表
    async handleInitFileList () {
      let obj = {
        readerDatasourceId: this.dataSource.database,
        readFilePath: this.dataSource.fileUrl
      }
      await browsingFiles(obj).then((res) => {
        let data = res.data
        console.log(res, "查询目录返回的下级目录")
        if (data.code === 200) {
          let gridDataArr = []
          data.content.forEach((item, index) => {
            gridDataArr.push({
              label: item.fileName,
              index: index,
              path: this.dataSource.fileUrl,
              type: item.type,
              children: []
            })
          })
          this.gridData = gridDataArr
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    async chooseTypeEvent () {
      if (!this.dataSource.databaseType) { return }
      let obj = {
        type: this.dataSource.databaseType
      }
      await typeGetDataSource(obj).then((res) => {
        let data = res.data
        if (data.code === 200) {
          this.databaseOptions = data.content
          this.dataSource.database = this.initData.readerDatasourceId
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    // 返回上一级文件
    handlePrevious () {
      this.dataSource.fileName = ""
      const result = this.dataSource.fileUrl.split("/")
      console.log(result)
      result.pop()
      this.dataSource.fileUrl = result.join("/")
      if (this.dataSource.fileUrl === "") {
        this.dataSource.fileUrl = "/"
      }
      this.handleInitFileList()
      console.log(this.gridData)
    },
    handleCloseDialog () {
      this.gridData = []
    },
    handleNodeClick (data) {
      this.NodeClickData = data
      console.log(data, "clickdata-------------")
      this.handleBrowsingFiles(data)
    },
    async handleBrowsingFiles (clickdata) {
      if (this.dataSource.database === "") {
        this.$message({
          message: "请先选择数据源",
          type: "error"
        })
        return
      }
      if (!this.dataSource.fileUrl) {
        this.$message({
          message: "请输入文件路径",
          type: "error"
        })
        return
      }
      this.dialogTableVisible = true
      console.log(clickdata, "点击的数据是这个")
      if (clickdata.label && clickdata.type !== 2) {
        this.dataSource.fileName = clickdata.label
        this.dataSource.fileUrl = clickdata.path
        return
      }
      let obj = {
        readerDatasourceId: this.dataSource.database,
        readFilePath: clickdata.label ? clickdata.path + "/" + clickdata.label : this.dataSource.fileUrl
      }
      await browsingFiles(obj).then((res) => {
        let data = res.data
        console.log(res, "查询目录返回的下级目录")
        if (data.code === 200) {
          this.dialogTableVisible = true
          // 首次进入dialog渲染最外层tree
          if (!clickdata.label) {
            data.content.forEach((item, index) => {
              this.gridData.push({
                label: item.fileName,
                path: this.dataSource.fileUrl,
                type: item.type,
                children: []
              })
            })
          }
          if (clickdata.label && clickdata.children.length === 0) {
            let fullFileName = ""
            let fileUrlIsEmpty = this.dataSource.fileUrl === "/" ? "" : this.dataSource.fileUrl
            data.content.forEach((item, index) => {
              clickdata.children.push({
                label: item.fileName,
                type: item.type,
                path: fileUrlIsEmpty + "/" + clickdata.label,
                children: []
              })
              fullFileName += item.fileName + "/"
            })
            fullFileName = fullFileName.substring(0, fullFileName.length - 1)
            this.dataSource.fileName = fullFileName
            this.dataSource.fileUrl = clickdata.path
          }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
      console.log(this.gridData)
    },
    async chooseTypeEvent () {
      if (!this.dataSource.databaseType) { return }
      let obj = {
        type: this.dataSource.databaseType
      }
      await typeGetDataSource(obj).then((res) => {
        let data = res.data
        if (data.code === 200) {
          this.databaseOptions = data.content
          this.dataSource.database = this.initData.readerDatasourceId
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    handlePageChange (page) {
      this.page = page
      this.chooseTableEvent()
    },
    handleGetSelection (data) {
      this.dataSource = {
        ...this.dataSource
        // selection: data
      }
    },
    // 校验数据
    validateForm () {
      let flag = true
      if (!this.dataSource.databaseType || !this.dataSource.database || !this.dataSource.fileUrl) {
        flag = false
        this.$message({
          message: "字段列表不能为空",
          type: "error"
        })
        return flag
      }

      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },
    setRules () {
      this.formRules = {
        databaseType: [{ required: true, message: "不能为空" }],
        database: [{ required: true, message: "不能为空" }],
        fileUrl: [{ required: true, message: "不能为空" }]
      }
    }
  },
  mounted () {
    this.setRules()
  }
};
</script>
<style lang="scss" scoped>
.dataSource {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
  .transfer {
    width: 600px;
    // max-height: 420px;
    // border: 1px solid red;
  }
}
</style>
<style lang="scss">
.dataSource {
  .transfer {
    .el-transfer-panel__body {
      height: 346px;
    }
    .el-transfer-panel__list {
      height: 300px;
    }
  }
}
</style>
